const { bfmetaSDK } = require('../../../util/util')
const { signature } = require('../../../util/signature')

const trToExchangeAny = () => {
    return async (req, res, next) => {
        try {
            if(!req.body.toExchangeSource || !req.body.toExchangeParentAssetType || !req.body.toExchangeAssetType || !req.body.toExchangeAssetPrealnum || !req.body.beExchangeSource|| !req.body.beExchangeParentAssetType || !req.body.beExchangeAssetType || !req.body.publicKey || !req.body.secretKey) {
                return res.status(400).send({
                    success: false,
                    message: "参数不能为空"
                })
            }
            let data = {
                toExchangeSource: req.body.toExchangeSource,
                toExchangeChainName: req.body.toExchangeChainName,
                toExchangeParentAssetType: req.body.toExchangeParentAssetType, //number
                toExchangeAssetType: req.body.toExchangeAssetType,
                toExchangeAssetPrealnum: req.body.toExchangeAssetPrealnum,
                beExchangeSource: req.body.beExchangeSource,
                beExchangeChainName: req.body.beExchangeChainName,
                beExchangeParentAssetType: req.body.beExchangeParentAssetType, //number
                beExchangeAssetType: req.body.beExchangeAssetType,
                beExchangeAssetPrealnum: req.body.beExchangeAssetPrealnum,
                publicKey: req.body.publicKey,
                fee: "2000",
                applyBlockHeight: 1
            }
            // 创建资产交换事件
            let result = await bfmetaSDK.api.transaction.createToExchangeAny(data)
            if(!result.success){
                return res.status(400).send(result)
            }
            // 对该事件签名
            const _signature = await signature(result.result.buffer, req.body.secretKey)
            data = {
                signature: _signature,
                buffer: result.result.buffer
            }
            // 广播创建资产交换事件
            result = await bfmetaSDK.api.transaction.broadcastToExchangeAny(data)
            if(!result.success){
                return res.status(400).send(result)
            }
            res.status(200).send(result)
        } catch (error) {
            next(error)
        }
    }
}

module.exports = { trToExchangeAny }